<?php
include_once('./config/config.php');
// 判断是否已经登录
if (isset($_COOKIE['LoginAdmin'])) {
    ShowMsg('你已登录，无须重复登录');
}

if ($_POST) {
    // 接收验证码
    $imgcode = $_POST['imgcode'];
    if (empty($imgcode)) {
        ShowMsg('请输入验证码');
    }
    // 判断验证码跟session会话的值是否相等
    if (strtoupper($imgcode) != strtoupper($_SESSION['imgcode'])) {
        ShowMsg('验证码错误，请重新输入');
    }
    // 接收用户名以及密码
    $username = $_POST['username'];
    $password = $_POST['password'];
    // 判断是否为空
    if (empty($username)) {
        ShowMsg('请输入用户名');
    }
    if (empty($password)) {
        ShowMsg('请输入密码');
    }
    // 查询语句
    $sql = "select * from `pre_admin` where `username`='$username'";
    $admin = find($sql);
    if (!$admin) {
        ShowMsg('用户不存在，请重新输入');
    }
    // 用查询出来的密码盐拼接输入的密码再md5加密
    if (md5($password . $admin['salt']) != $admin['password']) {
        ShowMsg('密码错误，请重新输入');
    }

    // 封装数据
    $data = [
        'id' => $admin['id'],
        'username' => $admin['username'],
        'avatar' => $admin['avatar'],
    ];

    // 把数组转成json格式
    $Json = json_encode($data);
    // 设置cookie
    setcookie('LoginAdmin', $Json);
    ShowMsg('登录成功', 'index.php');
}
?>

<!DOCTYPE html>
<html lang="en">

<head>
    <!-- 引入公共样式 -->
    <?php include_once('./common/meta.php'); ?>
    <!-- 引入公共js -->
    <?php include_once('./common/script.php'); ?>
</head>
<style>
    input[name='imgcode'] {
        width: 77% !important;
    }

    .imgcode {
        margin-top: -9px;
    }
</style>

<body>
    <div class="navbar">
        <div class="navbar-inner">
            <a class="brand" href="index.php"><span class="second">Admin</span></a>
        </div>
    </div>

    <div class="row-fluid">
        <div class="dialog">
            <div class="block">
                <p class="block-heading">登录</p>
                <div class="block-body">
                    <form method="post">
                        <label>用户名</label>
                        <input type="text" class="span12" name="username">
                        <label>密码</label>
                        <input type="password" class="span12" name="password">
                        <label>验证码</label>
                        <div>
                            <input type="text" class="span12" name="imgcode">
                            <img src="config/imgcode.php" alt="" class="imgcode" onclick="this.src = 'config/imgcode.php?id='+Math.random()">
                        </div>
                        <button class="btn btn-primary pull-right">登录</button>
                        <div class="clearfix"></div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</body>

</html>